package com.ruoyi.school.service.impl;

import java.util.List;

import com.google.gson.Gson;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.school.Exception.BussnissExecption;
import com.ruoyi.school.domain.Love;
import com.ruoyi.school.domain.User;
import com.ruoyi.school.domain.WeChatSessionModel;
import com.ruoyi.school.mapper.LoveMapper;
import com.ruoyi.school.mapper.UserMapper;
import com.ruoyi.school.service.ILoveService;
import com.ruoyi.school.service.MinioService;
import com.ruoyi.school.untils.FileTypeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.school.mapper.SchoolNewsMapper;
import com.ruoyi.school.domain.SchoolNews;
import com.ruoyi.school.service.ISchoolNewsService;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 消息维护Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-15
 */
@Service
@Slf4j
public class SchoolNewsServiceImpl implements ISchoolNewsService 
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MinioService minioService;

    @Autowired
    private SchoolNewsMapper schoolNewsMapper;

    @Autowired
    LoveMapper loveMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${APPID}")
    private String appid;

    @Value("${APPSECRET}")
    private String appsecret;

    /**
     * 查询消息维护
     * 
     * @param id 消息维护主键
     * @return 消息维护
     */
    @Override
    public SchoolNews selectSchoolNewsById(Long id)
    {
        return schoolNewsMapper.selectSchoolNewsById(id);
    }

    /**
     * 查询消息维护列表
     * 
     * @param schoolNews 消息维护
     * @return 消息维护
     */
    @Override
    public List<SchoolNews> selectSchoolNewsList(SchoolNews schoolNews)
    {
        return schoolNewsMapper.selectSchoolNewsList(schoolNews);
    }

    @Override
    public int updateSchoolNews(SchoolNews schoolNews) {
        return schoolNewsMapper.updateSchoolNews(schoolNews);
    }


    @Override
    public List<SchoolNews> selectSchoolNewsListById(Long userId) {

        return schoolNewsMapper.selectSchoolNewsListById(userId);
    }

    @Override
    public User handleFileUpload(MultipartFile file, String nickName, String code) {
           //上传图片
        String picUrl="https://q1.itc.cn/q_70/images03/20240315/5e851fd8654c43eeacea8da4d0fbb56b.jpeg";
        String fileType = FileTypeUtils.getFileType(file);
        if (fileType!=null) {
             picUrl = minioService.putObject(file, "school", fileType);
        }

//           String picUrl="https://q1.itc.cn/q_70/images03/20240315/5e851fd8654c43eeacea8da4d0fbb56b.jpeg";
            // 根据传入code，调用微信服务器，获取唯一openid
            // 微信服务器接口地址
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret
                    + "&js_code=" + code + "&grant_type=authorization_code";
            String errmsg = "";
            String errcode = "";
            String session_key = "";
            String openid = "";
            WeChatSessionModel weChatSessionModel;
            // 发送请求
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
            // 判断请求是否成功
            if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                // 获取主要内容
                String sessionData = responseEntity.getBody();
                Gson gson = new Gson();
                //将json字符串转化为实体类;
                weChatSessionModel = gson.fromJson(sessionData, WeChatSessionModel.class);
                log.info("返回的数据==>{}", weChatSessionModel);
                //获取用户的唯一标识openid
                openid = weChatSessionModel.getOpenid();
                //获取错误码
                errcode = weChatSessionModel.getErrcode();
                //获取错误信息
                errmsg = weChatSessionModel.getErrmsg();
                session_key = weChatSessionModel.getSession_key();
            } else {
                log.info("出现错误，错误信息：{}", errmsg);
                throw new BussnissExecption(errmsg);
            }
            // 判断是否成功获取到openid
            if ("".equals(openid) || openid == null) {
                log.info("错误获取openid,错误信息:{}", errmsg);
                throw new BussnissExecption(errmsg);
            } else {
                // 判断用户是否存在，查询数据库
                User userInfo=userMapper.getObjByOpenid(openid);
                // 不存在，加入数据表
                if (userInfo == null) {
                    // 填充初始信息
                    // 加入数据表
                    //状态 1禁用 0正常 2审核
                    User user = new User(null,nickName,picUrl,session_key,openid,"0");
                    userMapper.insertUser(user);
                    return user;
                } else {
                    if (!userInfo.getStatus().equals('1')){
                        userInfo.setUserName(nickName);
                        userInfo.setUserPic(picUrl);
                        userMapper.updateUser(userInfo);
                        updateUser(userInfo.getId(),userInfo.getUserPic());
                        return userInfo;
                    }else {
                        throw new BussnissExecption("账号被禁，请联系管理员");
                    }
                }
            }
    }

    public void updateUser(Long userId,String picUrl){
        Love love = new Love().setUserId(userId);
        List<Love> loveList = loveMapper.selectLoveList(love);
        if (loveList.size()>0){
            for (Love love1 : loveList) {
                love1.setUserPic(picUrl);
                loveMapper.updateLove(love1);
            }
        }
    }
}
